<?php
/**
 * Процедуры и функции работы с каталогом
 * @category ОбщиеФункции
 */

require_once('config.php');
require_once(DIR_SYSTEM . 'library/db.php');
require_once('cml_exchange.php');

//**************************************************************************************
// Процедуры работы с категориями
function find_group_by_uuid($uuid, &$db) {
    //$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    $query = $db->query("SELECT * FROM `" . DB_PREFIX . "category` WHERE `uuid` = '" . (string) $uuid . "' ");

    return $query->row;
}

function create_new_group(&$data, &$db) {

 //   echo "(bool)strcmp(\$data['parent_uuid'], NULL_UUID) " . strcmp($data['parent_uuid'], NULL_UUID) . "\t" . $data['parent_uuid'] . "\n";

    if (strcasecmp($data['parent_uuid'], NULL_UUID) == 0 ) {
        $parent_id = 0;
    } else {
        $group_by_uuid = find_group_by_uuid($data['parent_uuid'], $db);
        $parent_id = $group_by_uuid['category_id'];
    }

    $data['parent_id'] = (int) $parent_id;

    $db->query("INSERT INTO " . DB_PREFIX . "category SET parent_id = '" . (int) $data['parent_id'] . "', sort_order = '" . (int) $data['sort_order'] . "', date_modified = NOW(), date_added = NOW(), `uuid` = '" . (string)$data['uuid'] . "', `parent_uuid` = '" . (string)$data['parent_uuid'] . "'");

    $category_id = $db->getLastId();

    $data['category_id'] = (int) $category_id;

    if (isset($data['image'])) {
        $db->query("UPDATE " . DB_PREFIX . "category SET image = '" . $db->escape($data['image']) . "' WHERE category_id = '" . (int) $category_id . "'");
    }

    foreach ($data['category_description'] as $language_id => $value) {
        $db->query("INSERT INTO " . DB_PREFIX . "category_description SET category_id = '" . (int) $category_id . "', language_id = '" . (int) $language_id . "', name = '" . $db->escape($value['name']) . "', meta_description = '" . $db->escape($value['meta_description']) . "', description = '" . $db->escape($value['description']) . "'");
    }

    if ($data['keyword']) {
        $db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'category_id=" . (int) $category_id . "', keyword = '" . $db->escape($data['keyword']) . "'");
    }

}

function update_group($data, &$db) {
    $db_group_data = find_group_by_uuid($data['uuid'], $db);
    if (($db_group_data['parent_uuid'] != $data['parent_uuid']) || ($db_group_data['name'] != $data['name'])) {

        // Надо обновить инфу!!!
        // Наименование
        $name = $data['name'];
        $uuid = $data['uuid'];
        $parent_uuid = $data['parent_uuid'];
        //$query = $db->query("UPDATE " . DB_PREFIX . "excahnge_1c_catalog SET `name` = '" . $name . "' WHERE (`uuid` = '" . $uuid . "');");

        //Подчинение
        // Найдем категорию по ИД
        if (strcasecmp($data['parent_uuid'], NULL_UUID) == 0) {
            $parent_category_id = 0;
        } else {
            $parent_category_data = find_group_by_uuid($data['parent_uuid'], $db);
            $parent_category_id = $parent_category_data['category_id'];
        }
        ;

        $data['parent_id'] = (int) $parent_category_id;
        $category_id = $db_group_data['category_id'];

        $db->query("UPDATE " . DB_PREFIX . "category SET parent_id = '" . (int) $data['parent_id'] . "', sort_order = '" . (int) $data['sort_order'] . "', date_modified = NOW(), `parent_uuid` = '" . (string)$data['parent_uuid'] . "'  WHERE category_id = '" . (int) $category_id . "'");

        if (isset($data['image'])) {
            $db->query("UPDATE " . DB_PREFIX . "category SET image = '" . $db->escape($data['image']) . "' WHERE category_id = '" . (int) $category_id . "'");
        }

        $db->query("DELETE FROM " . DB_PREFIX . "category_description WHERE category_id = '" . (int) $category_id . "'");

        foreach ($data['category_description'] as $language_id => $value) {
            $db->query("INSERT INTO " . DB_PREFIX . "category_description SET category_id = '" . (int) $category_id . "', language_id = '" . (int) $language_id . "', name = '" . $db->escape($value['name']) . "', meta_description = '" . $db->escape($value['meta_description']) . "', description = '" . $db->escape($value['description']) . "'");
        }


        $db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'category_id=" . (int) $category_id . "'");

        if ($data['keyword']) {
            $db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'category_id=" . (int) $category_id . "', keyword = '" . $db->escape($data['keyword']) . "'");
        }

    }

}

function create_array_of_groups($xml, $parent_uuid, &$data, &$db) {
    if (isset($xml->{"Группы"})) {
        foreach ($xml->{"Группы"}->{"Группа"} as $category_data) {
            $group_item = array(
                'uuid' => (string) $category_data->{"Ид"},
                'parent_uuid' => (string) $parent_uuid,
                'category_name' => (string) $category_data->{"Наименование"},
                'category_id' => 0,
                'isnew' => false,
                'modified' => false,
                // стандартные данные
                'id' => 0,
                'parent_id' => 0,
                'sort_order' => '0',
                'status' => '1',
                'category_store' => '1',
                'category_description' => array(
                    // 1 = Язык по умолчанию!
                    1 => array(
                        'name' => (string) $category_data->{"Наименование"},
                        'meta_description' => '',
                        'description' => ''
                    )
                ),
                'keyword' => false,
                'category_store' => array(
                    0 //Default store
                ),
            );

            $uuid = $group_item['uuid'];
            $result = find_group_by_uuid($uuid, $db);
            if (count($result) == 0) {
                create_new_group($group_item, $db);
            } else {
                update_group($group_item, $db);
            }

            $data[] = $group_item;

            if (isset($category_data->{"Группы"})) {
                create_array_of_groups($category_data, $category_data->{"Ид"}, $data, $db);
            }
        }
    }

}

function parse_groups($dir) {
    $xml = simplexml_load_file($dir . '/import.xml');
    $groups_xml = $xml->{"Классификатор"};
    $data = array();
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

    create_array_of_groups($groups_xml, NULL_UUID, $data, $db);

}

// процедуры работы с товарами

function find_product_by_uuid($uuid, &$db) {
    /* @var $query DB */
    $query = $db->query("SELECT * FROM `" . DB_PREFIX . "product` WHERE `uuid` = '" . (string) $uuid . "' ");

    return $query->row;
}

function create_product(&$data, &$db) {
    //$query = $db->query("INSERT INTO `" . DB_PREFIX . "exchange_1c_sku` (`uuid`, `sku`, `name`, `parent_group_uuid`, `id`, `group_id` ) VALUES ('" . $data['uuid'] . "', '" . $data['sku'] . "', '" . $data['model'] . "', '" . $data['group_uuid'] . "', '0', '0');");
    $db->query("INSERT INTO " . DB_PREFIX . "product SET model = '" . $db->escape($data['model']) . "', sku = '" . $db->escape($data['sku']) . "', location = '" . $db->escape($data['location']) . "', quantity = '" . (int)$data['quantity'] . "', stock_status_id = '" . (int)$data['stock_status_id'] . "', date_available = '" . $db->escape($data['date_available']) . "', manufacturer_id = '" . (int)$data['manufacturer_id'] . "', shipping = '" . (int)$data['shipping'] . "', price = '" . (float)$data['price'] . "', weight = '" . (float)$data['weight'] . "', weight_class_id = '" . (int)$data['weight_class_id'] . "', length = '" . (float)$data['length'] . "', width = '" . (float)$data['width'] . "', height = '" . (float)$data['height'] . "', measurement_class_id = '" . (int)$data['measurement_class_id'] . "', status = '" . (int)$data['status'] . "', tax_class_id = '" . (int)$data['tax_class_id'] . "', date_added = NOW(), `uuid` = '" . $data['uuid'] . "'");

    $product_id = $db->getLastId();

    if (isset($data['image'])) {
            $db->query("UPDATE " . DB_PREFIX . "product SET image = '" . $db->escape($data['image']) . "' WHERE product_id = '" . (int)$product_id . "'");
    }

    foreach ($data['product_description'] as $language_id => $value) {
            $db->query("INSERT INTO " . DB_PREFIX . "product_description SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', name = '" . $db->escape($value['name']) . "', meta_description = '" . $db->escape($value['meta_description']) . "', description = '" . $db->escape($value['description']) . "'");
    }

    if (isset($data['product_option'])) {
            foreach ($data['product_option'] as $product_option) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', sort_order = '" . (int)$product_option['sort_order'] . "'");

                    $product_option_id = $db->getLastId();

                    foreach ($product_option['language'] as $language_id => $language) {
                            $db->query("INSERT INTO " . DB_PREFIX . "product_option_description SET product_option_id = '" . (int)$product_option_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $db->escape($language['name']) . "'");
                    }

                    if (isset($product_option['product_option_value'])) {
                            foreach ($product_option['product_option_value'] as $product_option_value) {
                                    $db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET product_option_id = '" . (int)$product_option_id . "', product_id = '" . (int)$product_id . "', quantity = '" . (int)$product_option_value['quantity'] . "', subtract = '" . (int)$product_option_value['subtract'] . "', price = '" . (float)$product_option_value['price'] . "', prefix = '" . $db->escape($product_option_value['prefix']) . "', sort_order = '" . (int)$product_option_value['sort_order'] . "'");

                                    $product_option_value_id = $db->getLastId();

                                    foreach ($product_option_value['language'] as $language_id => $language) {
                                            $db->query("INSERT INTO " . DB_PREFIX . "product_option_value_description SET product_option_value_id = '" . (int)$product_option_value_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $db->escape($language['name']) . "'");
                                    }
                            }
                    }
            }
    }

    if (isset($data['product_discount'])) {
            foreach ($data['product_discount'] as $value) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_discount SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', quantity = '" . (int)$value['quantity'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $db->escape($value['date_start']) . "', date_end = '" . $db->escape($value['date_end']) . "'");
            }
    }

    if (isset($data['product_special'])) {
            foreach ($data['product_special'] as $value) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_special SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $db->escape($value['date_start']) . "', date_end = '" . $db->escape($value['date_end']) . "'");
            }
    }

    if (isset($data['product_image'])) {
            foreach ($data['product_image'] as $image) {
            $db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int)$product_id . "', image = '" . $db->escape($image) . "'");
            }
    }

    if (isset($data['product_download'])) {
            foreach ($data['product_download'] as $download_id) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_to_download SET product_id = '" . (int)$product_id . "', download_id = '" . (int)$download_id . "'");
            }
    }

    if (isset($data['product_category'])) {
            foreach ($data['product_category'] as $category_id) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_to_category SET product_id = '" . (int)$product_id . "', category_id = '" . (int)$category_id . "'");
            }
    }

    if (isset($data['product_related'])) {
            foreach ($data['product_related'] as $related_id) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");
            }
    }

    if ($data['keyword']) {
            $db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $db->escape($data['keyword']) . "'");
    }

}

function update_product(&$data, &$db) {
    $product = find_product_by_uuid($data['uuid'], $db);
    $product_id = $product['id'];
    $data['id'] = $product['id'];
    //$query = $db->query('UPDATE ' . DB_PREFIX . 'exchange_1c_sku SET `sku` = "' . $data['sku'] . '", `name` = "' . $data['model'] . '" , `parent_group_uuid` = "' . $data['group_uuid'] . '" , `id` = ' . $product_id . ' , `group_id` = ' . $data['product_category'][0]['category_id'] . ' WHERE `uuid` = "' . $data['uuid'] . '"');
    $db->query("UPDATE " . DB_PREFIX . "product SET model = '" . $db->escape($data['model']) . "', sku = '" . $db->escape($data['sku']) . "', location = '" . $db->escape($data['location']) . "', quantity = '" . (int)$data['quantity'] . "', stock_status_id = '" . (int)$data['stock_status_id'] . "', date_available = '" . $db->escape($data['date_available']) . "', manufacturer_id = '" . (int)$data['manufacturer_id'] . "', shipping = '" . (int)$data['shipping'] . "', price = '" . (float)$data['price'] . "', weight = '" . (float)$data['weight'] . "', weight_class_id = '" . (int)$data['weight_class_id'] . "', length = '" . (float)$data['length'] . "', width = '" . (float)$data['width'] . "', height = '" . (float)$data['height'] . "', measurement_class_id = '" . (int)$data['measurement_class_id'] . "', status = '" . (int)$data['status'] . "', tax_class_id = '" . (int)$data['tax_class_id'] . "', date_modified = NOW() WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['image'])) {
            $db->query("UPDATE " . DB_PREFIX . "product SET image = '" . $db->escape($data['image']) . "' WHERE product_id = '" . (int)$product_id . "'");
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_description WHERE product_id = '" . (int)$product_id . "'");

    foreach ($data['product_description'] as $language_id => $value) {
            $db->query("INSERT INTO " . DB_PREFIX . "product_description SET product_id = '" . (int)$product_id . "', language_id = '" . (int)$language_id . "', name = '" . $db->escape($value['name']) . "', meta_description = '" . $db->escape($value['meta_description']) . "', description = '" . $db->escape($value['description']) . "'");
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'");
    $db->query("DELETE FROM " . DB_PREFIX . "product_option_description WHERE product_id = '" . (int)$product_id . "'");
    $db->query("DELETE FROM " . DB_PREFIX . "product_option_value WHERE product_id = '" . (int)$product_id . "'");
    $db->query("DELETE FROM " . DB_PREFIX . "product_option_value_description WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_option'])) {
            foreach ($data['product_option'] as $product_option) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_option SET product_id = '" . (int)$product_id . "', sort_order = '" . (int)$product_option['sort_order'] . "'");

                    $product_option_id = $db->getLastId();

                    foreach ($product_option['language'] as $language_id => $language) {
                            $db->query("INSERT INTO " . DB_PREFIX . "product_option_description SET product_option_id = '" . (int)$product_option_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $db->escape($language['name']) . "'");
                    }

                    if (isset($product_option['product_option_value'])) {
                            foreach ($product_option['product_option_value'] as $product_option_value) {
                                    $db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET product_option_id = '" . (int)$product_option_id . "', product_id = '" . (int)$product_id . "', quantity = '" . (int)$product_option_value['quantity'] . "', subtract = '" . (int)$product_option_value['subtract'] . "', price = '" . (float)$product_option_value['price'] . "', prefix = '" . $db->escape($product_option_value['prefix']) . "', sort_order = '" . (int)$product_option_value['sort_order'] . "'");

                                    $product_option_value_id = $db->getLastId();

                                    foreach ($product_option_value['language'] as $language_id => $language) {
                                            $db->query("INSERT INTO " . DB_PREFIX . "product_option_value_description SET product_option_value_id = '" . (int)$product_option_value_id . "', language_id = '" . (int)$language_id . "', product_id = '" . (int)$product_id . "', name = '" . $db->escape($language['name']) . "'");
                                    }
                            }
                    }
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_discount'])) {
            foreach ($data['product_discount'] as $value) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_discount SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', quantity = '" . (int)$value['quantity'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $db->escape($value['date_start']) . "', date_end = '" . $db->escape($value['date_end']) . "'");
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_special WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_special'])) {
            foreach ($data['product_special'] as $value) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_special SET product_id = '" . (int)$product_id . "', customer_group_id = '" . (int)$value['customer_group_id'] . "', priority = '" . (int)$value['priority'] . "', price = '" . (float)$value['price'] . "', date_start = '" . $db->escape($value['date_start']) . "', date_end = '" . $db->escape($value['date_end']) . "'");
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_image'])) {
            foreach ($data['product_image'] as $image) {
            $db->query("INSERT INTO " . DB_PREFIX . "product_image SET product_id = '" . (int)$product_id . "', image = '" . $db->escape($image) . "'");
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_to_download WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_download'])) {
            foreach ($data['product_download'] as $download_id) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_to_download SET product_id = '" . (int)$product_id . "', download_id = '" . (int)$download_id . "'");
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_category'])) {
            foreach ($data['product_category'] as $category_id) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_to_category SET product_id = '" . (int)$product_id . "', category_id = '" . (int)$category_id . "'");
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "product_related WHERE product_id = '" . (int)$product_id . "'");

    if (isset($data['product_related'])) {
            foreach ($data['product_related'] as $related_id) {
                    $db->query("INSERT INTO " . DB_PREFIX . "product_related SET product_id = '" . (int)$product_id . "', related_id = '" . (int)$related_id . "'");
            }
    }

    $db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'product_id=" . (int)$product_id. "'");

    if ($data['keyword']) {
            $db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'product_id=" . (int)$product_id . "', keyword = '" . $db->escape($data['keyword']) . "'");
    }


}

function create_array_of_products($xml_product, &$data, &$db) {

    if (!((is_object($xml_product->{"Товары"})) && (!empty($xml_product->{"Товары"})))) {
        return 0;
    }
    foreach ($xml_product->{"Товары"}->{"Товар"} as $sku_data) {
        $product_groups = "";
        unset($product_groups);
        foreach ($sku_data->{"Группы"} as $groups) {
            $product_groups[] = (string) $groups->{"Ид"};
        }
        ;
        $group_uuid = $product_groups[0];
        $group_id = find_group_by_uuid($group_uuid, $db);

        $data_item = array(
            'uuid' => (string) $sku_data->{"Ид"},
            'group_uuid' => $group_uuid,
            'model' => htmlspecialchars($sku_data->{"Наименование"}),
            'sku' => (string) $sku_data->{"Артикул"},
            'id' => 0,
            'image' => '',
            'status' => '1',
            'location' => '',
            'quantity' => 0.0,
            'minimum' => '0',
            'subtract' => '0',
            'stock_status_id' => '7',
            'date_available' => '01/01/2010',
            'manufacturer_id' => '0',
            'shipping' => '1',
            'price' => 0.0,
            'cost' => '0',
            'weight' => '0.1',
            'weight_class_id' => '1',
            'length' => '0.1',
            'width' => '0.1',
            'height' => '0.1',
            'length_class_id' => '1',
            'status' => '1',
            'tax_class_id' => '0',
            'sort_order' => '0',
            'product_description' => array(
                1 => array(
                    'name' => htmlspecialchars($sku_data->{"Наименование"}),

                    'meta_description' => '',
                    'description' => ''
                )
            ),
            'product_store' => array(
                0
            ),
            'product_category' => array(
                $group_id['category_id']
            ),
            'product_tags' => array(
                0
            ),
            'keyword' => false,
        );

        $data[] = $data_item;
    }
}

function update_product_price(&$product_item, $xml_product_price) {
    //$result = $xml_product_price->xpath('//Предложение/Ид[ . ="'.$product_item['uuid'].'"]');
    $result = $xml_product_price->xpath('//Предложение[Ид="' . $product_item['uuid'] . '"]');
    $xml = $result[0];
    $product_item['price'] = (float) $xml->{"Цены"}->{"Цена"}->{"ЦенаЗаЕдиницу"};
    $product_item['quantity'] = (float) $xml->{"Количество"};
}

function update_products($data, &$db) {
    foreach ($data as $product_item) {
        $product = find_product_by_uuid($product_item['uuid'], $db);
        if (count($product) == 0) {
            create_product($product_item, $db);
        } else {
            update_product($product_item, $db);
        }

    }
}

function create_array_of_products2($xml_product, $xml_price, &$db) {

    if (!((is_object($xml_product->{"Товары"})) && (!empty($xml_product->{"Товары"})))) {
        return 0;
    }
    foreach ($xml_product->{"Товары"}->{"Товар"} as $sku_data) {
        $product_groups = "";
        unset($product_groups);
        foreach ($sku_data->{"Группы"} as $groups) {
            $product_groups[] = (string) $groups->{"Ид"};
        }
        ;
        $group_uuid = $product_groups[0];
        $group_id = find_group_by_uuid($group_uuid, $db);

        $data_item = array(
            'uuid' => (string) $sku_data->{"Ид"},
            'group_uuid' => $group_uuid,
            'model' => htmlspecialchars($sku_data->{"Наименование"}),
            'sku' => (string) $sku_data->{"Артикул"},
            'id' => 0,
            'image' => '',
            'status' => '1',
            'location' => '',
            'quantity' => 0.0,
            'minimum' => '0',
            'subtract' => '0',
            'stock_status_id' => '7',
            'date_available' => '01/01/2010',
            'manufacturer_id' => '0',
            'shipping' => '1',
            'price' => 0.0,
            'cost' => '0',
            'weight' => '0.1',
            'weight_class_id' => '1',
            'length' => '0.1',
            'width' => '0.1',
            'height' => '0.1',
            'length_class_id' => '1',
            'status' => '1',
            'tax_class_id' => '0',
            'sort_order' => '0',
            'product_description' => array(
                1 => array(
                    'name' => htmlspecialchars($sku_data->{"Наименование"}),

                    'meta_description' => '',
                    'description' => ''
                )
            ),
            'product_store' => array(
                0
            ),
            'product_category' => array(
                $group_id['category_id']
            ),
            'product_tags' => array(
                0
            ),
            'keyword' => false,
        );

        $product_item = $data_item;
        //update_product_price($data_item, $xml_price);
        $product = find_product_by_uuid($product_item['uuid'], $db);
        if (count($product) == 0) {
            create_product($product_item, $db);
        } else {
            update_product($product_item, $db);
        }
    }
}

function parse_products($dir) {

    $product_xml = simplexml_load_file($dir . '/import.xml');
    $product_price = simplexml_load_file($dir . '/offers.xml');
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    create_array_of_products2($product_xml->{"Каталог"}, $product_price->{"ПакетПредложений"}, $db);
//    foreach ($data as &$product_item) {
//        echo $product_item['model'] . "\n";
//        update_product_price($product_item, $product_price);
//    }
//    update_products($data, $db);
}

function parse_price($dir){
    $xml_product_price = simplexml_load_file($dir . '/offers.xml');
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    //get all products
    $query = $db->query("SELECT * FROM " . DB_PREFIX . "product WHERE `uuid` <> '" . NULL_UUID . "'");
    foreach ($query->rows as $product) {
        $product_uuid = (string)$product['uuid'];
        $result = $xml_product_price->xpath('//Предложение[Ид="' . $product_uuid . '"]');
        $xml = $result[0];
        $product_item_price = (float) $xml->{"Цены"}->{"Цена"}->{"ЦенаЗаЕдиницу"};
        $product_item_quantity = (int) $xml->{"Количество"};
        //Update
        $db->query("UPDATE " . DB_PREFIX . "product SET `quantity` = '" . (int)$product_item_quantity . "', `price` = '" . (float)$product_item_price . "' WHERE `product_id` = '" . $product['product_id'] . "'");
    }
    
}

//

function clear_database() {
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'category`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'category_description`;');
 
    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_description`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_discount`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_image`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_option`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_option_description`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_option_value`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_option_value_description`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_related`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_special`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_to_category`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'product_to_download`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'review`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'category`;');

    $db->query('TRUNCATE TABLE `' . DB_PREFIX . 'category_description`;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_description` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_discount` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_image` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_option` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_option_description` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_option_value` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_option_value_description` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_related` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_special` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_to_category` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'product_to_download` AUTO_INCREMENT = 0;');

    $db->query('ALTER TABLE `' . DB_PREFIX . 'review` AUTO_INCREMENT = 0;');

}

function parse_cml2($dir, $filename) {
    try {
        if ($filename === 'import.xml'){
            parse_groups($dir);
            parse_products($dir);
        } else if ($filename === 'offers.xml') {
            parse_price($dir);
        } else{
            parse_groups($dir);
            parse_products($dir);
            parse_price($dir);
        }
        echo "sucsess";
    }catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
}

?>
